package com.jiao.mydd.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源配置
 *
 * @author
 */
@Configuration
public class DataSourceConfig {
    public final static String WRITE_DATASOURCE_KEY = "writeDruidDataSource";
    public final static String READ_DATASOURCE_KEY = "readDruidDataSource";

    @Value("${spring.datasource.druid.connection-init-sqls}")
    private String connectionInitSqls;

    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    @Bean(name = READ_DATASOURCE_KEY)
    public DataSource readDruidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        List<String> initSqls = new ArrayList<>();
        initSqls.add(connectionInitSqls);
        dataSource.setConnectionInitSqls(initSqls);
        dataSource.setDefaultReadOnly(true);
        return dataSource;
    }

    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    @Bean(name = WRITE_DATASOURCE_KEY)
    public DataSource writeDruidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        List<String> initSqls = new ArrayList<>();
        initSqls.add(connectionInitSqls);
        dataSource.setConnectionInitSqls(initSqls);
        return dataSource;
    }


    @Bean
    @Primary
    public AbstractRoutingDataSource routingDataSource(
            @Qualifier(READ_DATASOURCE_KEY) DataSource readDruidDataSource,
            @Qualifier(WRITE_DATASOURCE_KEY) DataSource writeDruidDataSource) {
        DynamicDataSource dataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        targetDataSources.put(WRITE_DATASOURCE_KEY, writeDruidDataSource);
        targetDataSources.put(READ_DATASOURCE_KEY, readDruidDataSource);
        dataSource.setTargetDataSources(targetDataSources);// 配置数据源
        dataSource.setDefaultTargetDataSource(writeDruidDataSource);// 默认为主库用于写数据
        return dataSource;
    }
}
